__author__ = 'joey'

from numpy import *
import operator
import kNN

group, labels = kNN.createDataSet()
print group, labels

#[[ 1.   1.1]
# [ 1.   1. ]
#[ 0.   0. ]
#[ 0.   0.1]] ['A', 'A', 'B', 'B']

# 1 shape get size return eg. (4, 2)
print group.shape

#(4, 2)

# 2 tile
tile1 = tile((0, 0), (4, 1))
print tile1

#[[0 0]
# [0 0]
#[0 0]
#[0 0]]

# 3 tile - group
diffMat = tile1 - group
print diffMat

#[[-1.  -1.1]
# [-1.  -1. ]
# [ 0.   0. ]
#[ 0.  -0.1]]

# 4 diffMat ** 2
sqDiffMat = diffMat ** 2
print sqDiffMat

#[[ 1.    1.21]
# [ 1.    1.  ]
#[ 0.    0.  ]
#[ 0.    0.01]]

# 5 num
data = [[0, 1], [0, 5], [0, 2]]
print sum(data, axis=0)
print sum(data, axis=1)

sqDistances = sqDiffMat.sum(axis=1)
print sqDistances

#[ 2.21  2.    0.    0.01]

# 6 sqDiffMat ** 0.5
distances = sqDistances ** 0.5
print distances

#[ 1.48660687  1.41421356  0.          0.1       ]

# 7 argsort()
sortedDistIndicies = distances.argsort()
print sortedDistIndicies

#[2 3 1 0]

# 8 for i in range(k)
k = 3
classCount = {}
print classCount.get('A', 1)
for i in range(k):
    voteIlabel = labels[sortedDistIndicies[i]]
    classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
print classCount

# 9 sorted
print classCount.iteritems()
print operator.itemgetter(1)
sortedClassCount = sorted(classCount.iteritems(), key = operator.itemgetter(1), reverse=True)
print sortedClassCount

# 10 read file
fr = open("datingTestSet2.txt")
arrayOLines = fr.readlines()
print arrayOLines
numberOfLines = len(arrayOLines)
print numberOfLines
returnMat = zeros((numberOfLines, 3))
print returnMat
classLabelVector = []
index = 0
for line in arrayOLines:
    line = line.strip()
    listFromLine = line.split('\t')
    returnMat[index, :] = listFromLine[0:3]
    classLabelVector.append(int(listFromLine[-1]))
    index += 1
print returnMat, classLabelVector

# 11 array
# arrt = array([[1,2],[3,4]])
# print arrt[1, 0:2]
arrt = array([0, 1, 2, 3])
print arrt[0:3]

# 12 matplotlib
# datingDataMat, datingLabels = returnMat, classLabelVector
# import matplotlib
# import matplotlib.pyplot as plt
# fig = plt.figure()
# ax = fig.add_subplot(111)
# print datingLabels
# arr = 15.0 * array(datingLabels)
# print arr
# ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1], arr, arr)
# plt.show()

# 13 auto norm
print returnMat.min(0)
print array([[1,2],[3,4]])
t = array([5,6])
print tile(t, (3, 2))

minVals = returnMat.min(0)
maxVals = returnMat.max(0)
ranges = maxVals - minVals
m = returnMat.shape[0]
normDataSet = returnMat - tile(minVals, (m, 1))
normDataSet = normDataSet / tile(ranges, (m, 1))
print normDataSet










